package com.atguigu.gmall.common.exception.handler;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author lhh
 * @ClassName GlobalExceptionHandler
 * @date 2022 2022/12/10
 */
//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 与业务相关的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = GmallException.class)
    public Result handlerGmallException(GmallException e){
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return fail;

    }

    /**
     * 全局异常处理
     * @param exp
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result handlerException(Exception exp){
        Result<Object> fail = Result.fail();
        fail.setMessage(exp.getMessage());
        return fail;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        //异常结果
        BindingResult bindingResult = exception.getBindingResult();
        HashMap<String, String> hashMap = new HashMap<>();
        for (FieldError error : bindingResult.getFieldErrors()) {
            //错误属性
            String field = error.getField();
            //错误信息
            String defaultMessage = error.getDefaultMessage();
            hashMap.put(field, defaultMessage);
        }
        return Result.build(hashMap, ResultCodeEnum.INVAILD_PARAM);
    }
}
